﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows;
using ShredTheLog.Api.DataContracts;
using ShredTheLog.Api;
using System.Reflection;

namespace ShredTheLog.Converters
{
    [ValueConversion(typeof(Language?), typeof(ImageSource))]
    public sealed class FlagConverter : ConverterBase, IValueConverter
    {
        static FlagConverter()
        {
            var resourceDictionary = new ResourceDictionary() { Source = new Uri(@"pack://application:,,,/" + Assembly.GetExecutingAssembly().FullName + ";component/CountryFlags/Flags.xaml") };
            Flags = (FlagDescriptor[])resourceDictionary["Flags"];
            DefaultFlag = (ImageSource)resourceDictionary["DefaultFlag"];
            ScandinavianFlag = Flags.Single(i => i.Language == Language.Finnish).Image;
        }

        public static FlagDescriptor[] Flags { get; private set; }
        public static ImageSource DefaultFlag { get; private set; }
        public static ImageSource ScandinavianFlag { get; private set; }

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is Language)
                return Convert((Language)value);
            else
                return DefaultFlag;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException();
        }

        public static ImageSource Convert(Language language)
        {
            var item = Flags.SingleOrDefault(i => i.Language == language);
            if (item != null)
                return item.Image;
            else
                return DefaultFlag;
        }

        public static readonly FlagConverter Default = new FlagConverter();
    }

    public sealed class FlagDescriptor
    {
        public Language Language { get; set; }
        public ImageSource Image { get; set; }
    }
}
